const express = require('express'); //引入express
const router = express.Router();
const { Role } = require('../../models/roles');

// 增加角色
router.post('/add', (req, res) => {
	// console.log(req.body);
	const { name, menu } = req.body;
	let data = {
		name,
		menu: menu
	};
	console.log(data);
	new Role(data).save().then(role => {
		res.json({
			data: role,
			msg: '添加成功'
		});
	});
	res.json({ msg: 'login works' });
});
// 查询全部
router.get('/search', async (req, res) => {
	// .populate('menu')
	const data = await Role.find();
	global.log.desc = '查询全部角色';
	console.log(global.log, 'log');
	res.json({
		data: data,
		msg: '查询成功'
	});
});
// 通过id查询角色权限
router.get('/searchbyid/:id', async (req, res) => {
	const data = await Role.findById({ _id: req.params.id }).populate('menu');
	res.json({
		data: data,
		msg: '查询成功'
	});
});

// 修改角色权限
router.post('/updateRole/:id', (req, res) => {
	let menuItem = {
		name: req.body.name,
		menu: req.body.menu
	};
	global.log.desc = '角色修改';
	console.log(global.log, 'log');
	
	Role.findByIdAndUpdate(
		{ _id: req.params.id },
		{ $set: menuItem },
		{ new: true }
	)
		.then(profile => {
			res.json({
				code: 200,
				msg: '角色修改成功',
				data: profile
			});
		})
		.catch(err => {
			res.json({
				code: 400,
				msg: '角色修改失败',
				data: err
			});
		});
});
module.exports = router;
